package com.yanyeori.framework.jira.jiraclient;

import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.auth.BasicScheme;

import java.nio.charset.StandardCharsets;

/**
 * Basic HTTP authentication credentials.
 */
public class BasicCredentials implements ICredentials {

    private final String username;
    private final String password;

    /**
     * Creates new basic HTTP credentials.
     *
     * @param username 用户名
     * @param password 密码
     */
    public BasicCredentials(String username, String password) {
        this.username = username;
        this.password = password;
    }

    /**
     * Sets the Authorization header for the given request.
     *
     * @param req HTTP request to authenticate
     */
    public void authenticate(HttpRequest req) {
        Credentials creds = new UsernamePasswordCredentials(username, password);
        try {
            req.addHeader(new BasicScheme(StandardCharsets.UTF_8).authenticate(creds, req, null));
        } catch (AuthenticationException e) {
            throw new JiraException("BasicScheme.authenticate error", e);
        }
    }

    /**
     * Gets the logon name representing these credentials.
     *
     * @return logon name as a string
     */
    public String getLogonName() {
        return username;
    }

    public void initialize(RestClient client) throws JiraException {
    }

    public void logout(RestClient client) throws JiraException {
    }

}

